昨天我們試過了OpenTelemetry可以在functions內透過trace id和span id來追蹤。今天我們來用flask加上opentelemetry 追蹤我一些數值。
下面這邊截自 CNCF 在4/22好的一篇發文,有興趣的可以看看裡面有很詳細的說明 OpenTelemetry and Python: A complete instrumentation guide
那下面我們就來看一段flask + opentelemetry可以做到什麼
首先創造一個venv然後我們安裝flask和opentelemtry
pip install flask
pip install opentelemetry-distro
接下來我們寫一個app.py
from opentelemetry import trace
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.sdk.trace.export import ConsoleSpanExporter
provider = TracerProvider()
processor = BatchSpanProcessor(ConsoleSpanExporter())
provider.add_span_processor(processor)
trace.set_tracer_provider(provider)
tracer = trace.get_tracer(__name__)
前面我們設置一些opentelemetry 的provider processor和 trace
接下來就可以在code裡面加上
from random import randint
from flask import Flask, request
app = Flask(__name__)
@app.route("/roll")
def roll():
with tracer.start_as_current_span(
"server_request",
attributes={ "endpoint": "/roll" }
):
sides = int(request.args.get('sides'))
rolls = int(request.args.get('rolls'))
return roll_sum(sides,rolls)
def roll_sum(sides, rolls):
span = trace.get_current_span()
sum = 0
for r in range(0,rolls):
result = randint(1,sides)
span.add_event( "log", {
"roll.sides": sides,
"roll.result": result,
})
sum += result
return str(sum)
使用 trace.start_as_current_span 和 trace.get_current_span()來讓process 輸出到console上
接下來可以使用
flask run
來執行
然後我們做個curl
curl 'http://127.0.0.1:5000/roll?sides=10&rolls=1'
10面骰子骰一次
從flask console就可以看到
127.0.0.1 - - [06/Oct/2022 21:07:27] "GET /roll?sides=10&rolls=1 HTTP/1.1" 200 -
{
"name": "server_request",
"context": {
"trace_id": "0xc58684710f70860f47fb9a45614c9be8",
"span_id": "0x25b0982d63012c4b",
"trace_state": "[]"
},
"kind": "SpanKind.INTERNAL",
"parent_id": null,
"start_time": "2022-10-06T13:07:27.033325Z",
"end_time": "2022-10-06T13:07:27.033540Z",
"status": {
"status_code": "UNSET"
},
"attributes": {
"endpoint": "/roll"
},
"events": [
{
"name": "log",
"timestamp": "2022-10-06T13:07:27.033472Z",
"attributes": {
"roll.sides": 10,
"roll.result": 3
}
}
],
"links": [],
"resource": {
"attributes": {
"telemetry.sdk.language": "python",
"telemetry.sdk.name": "opentelemetry",
"telemetry.sdk.version": "1.13.0",
"service.name": "unknown_service"
},
"schema_url": ""
}
}
裡面包含著各種擲骰子的參數
"events": [
{
"name": "log",
"timestamp": "2022-10-06T13:07:27.033472Z",
"attributes": {
"roll.sides": 10,
"roll.result": 3
}
}
],
這樣每次在call /roll這個api我們就可以做追蹤了